package com.hy.controller;

import com.hy.common.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class UploadController {
    @Value("${upload.teacher-avatar-path}")
    private String uploadPath;

    /**
     * 图片上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result<String> uploadTeacherAvatar(@RequestParam("file") MultipartFile file) {
        try {
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || originalFilename.isEmpty()) {
                return Result.error("文件名为空");
            }
            String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFileName = UUID.randomUUID().toString() + fileSuffix;

            File destDir = new File(uploadPath);
            if (!destDir.exists()) {
                destDir.mkdirs(); // 创建目录
            }
            File destFile = new File(uploadPath + newFileName);
            file.transferTo(destFile); // 保存文件

            String accessUrl = "/teacher-avatar/" + newFileName;
            return Result.success(accessUrl); // 返回可访问路径
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("上传失败：" + e.getMessage());
        }
    }
}
